import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import com.google.gson.Gson;



public class SocketClinetTwo {
	private static int serverPort = 9999;	//port
	private static InetAddress serverIp ;	//IP
	private static String user = "Go";		//使用者姓名
	private static Scanner scanner;		//輸入端
	static Socket clientSocket;				// 客戶端socket
	static String tmp;						// 暫存文字訊息
	
	public static void main(String[] args) {		
		Thread t = new Thread(readData);
		t.start();
		while (true) {
			onWaitUserType();
		}
	}
	
	public static void onWaitUserType() {
		try {
			serverIp = InetAddress.getByName("192.168.132.1");
			clientSocket = new Socket(serverIp, serverPort);
			if(clientSocket.isConnected()){				
				BufferedWriter bw;
				// 取得網路輸出串流
				System.out.print("\n"+user+":");
				scanner = new Scanner(System.in);
				bw = new BufferedWriter( new OutputStreamWriter
						(clientSocket.getOutputStream()));		
				bw.write(getGsonString()+"\n");
				bw.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public static String getGsonString() {
		//時間
		SimpleDateFormat sdFormat = new SimpleDateFormat("a hh:mm:ss");
		Date today = new Date();
		//使用者
		String name = user;
		//訊息		
		String message = scanner.next();		
		Message msg = new Message(name, message ,sdFormat.format(today));
		Gson gson = new Gson();	
		// 將Message物件轉成JSON
		String json = gson.toJson(msg);
		return json;
	}
	
	// 取得網路訊息，這邊不需要改
	private static Runnable readData = new Runnable() {
		public void run() {
			
			try {
				// 以內定(本機電腦端)IP為Server端
				serverIp = InetAddress.getByName("192.168.132.1");
				clientSocket = new Socket(serverIp, serverPort);			
				// 取得網路輸入串流
				BufferedReader br = new BufferedReader(new InputStreamReader(
						clientSocket.getInputStream(),"UTF-8"));
				
				// 當連線後
				while (clientSocket.isConnected()) {					
					// 取得網路訊息
					tmp = br.readLine();					
					// 如果不是空息則
					if(tmp!=null)
						// 顯示新的訊息
						System.out.println(tmp+"\n");
				}
			} catch (IOException e) {
				
			}
		}
	};
	
}
